<?php
/**
 * 充值操作类
 * Created		: 2012-05-28
 * Modified		: 2012-07-07
 * @version		: 1.0.0
 * @author		: Joseph Chen (chenliq@gmail.com)
 */
class Pay 
{
	/**
	 * 充值记录表
	 * @var string
	 */
	public static $tbl = 'pay_order_log';
	/**
	 * 错误提示信息
	 * @var string
	 */
	public static $msg = '';
	/**
	 * 充值方式列表缓存key
	 * @var string
	 */
	public static $pmlKey = 'paymode-list';
	/**
	 * 充值方式缓存key前缀
	 * @var string
	 */
	public static $pmPreKey = 'paymode:';
	
	/**
	 * 读取一个支付方式信息
	 * @param int $id
	 */
	public static function readPayMode($id) 
	{
		$info = Cache::getHash(self::$pmPreKey.$id);
		if (!$info) {
			$model = new Model('pay_mode');
			$info = $model->read($id);
			if (!$info) {
				return false;
			}
			Cache::setHash(self::$pmPreKey.$id, $info);
		}
		return $info;
	}
	
	/**
	 * 获取支付方式列表
	 * @param int $status
	 * @return array
	 */
	public static function getPayModeList()
	{
		$list = null;
		$idList = Cache::lRange(self::$pmlKey, 0, -1);
		if ($idList) {
			foreach ($idList as $id) 
			{
				$tmp = Cache::getHash(self::$pmPreKey.$id);
				if (!$tmp) {
					$list = null;
					break;
				}
				$list[] = $tmp;
			}
		} 

		if (!$list) {
			$list = self::recacheAllPayMode();
		}
		
		return $list;
	}
	
	/**
	 * 重新缓存所有的支付方式
	 * @return array
	 */
	public static function recacheAllPayMode()
	{
		$model = new Model('pay_mode');
		$order = 'orderid asc,id asc';
		$list = $model->where('status=1')->order($order)->select();
		Cache::delete(self::$pmlKey);
		foreach ($list as $v) {
			if ($v['status']!=1) {
				continue;
			}
			Cache::rPush(self::$pmlKey, $v['id']);
			Cache::setHash(self::$pmPreKey.$v['id'], $v);
		}
		return $list;
	}
	
	/**
	 * 清除过期的待支付订单(默认超过30天)
	 * @param int $expire
	 */
	public static function clearExpirePayOrder($expire=2592000) 
	{
		$commitTime = time() - $expire;
		Db::delete('pay_order_log', 'create_time<='.$commitTime);
		return true;
	}
	
	/**
	 * 生成订单号
	 */
	public static function generateOrderNo()
	{
		switch ($GLOBALS['_orderno_type'])
		{
			case 1:
				$time = explode(' ', microtime());
				return date('YmdHis').substr($time[0], 2).mt_rand(0, 0xffff);
			break;
			
			case 2:
				return sha1(uniqid().Ip::getIp().mt_rand(0, 0xffff));
			break;
			
			case 3:
				return sprintf(
					'%04x%s%04x', 
					mt_rand(0, 0xffff), 
					md5(uniqid().Ip::getIp()), 
					mt_rand(0, 0xffff)
				);
			break;
			
			default:
				return sha1(uniqid().mt_rand(0, 0xffff));
			break;
		}
	}
}
